package pers.sports.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import pers.sports.dao.StudentDao;
import pers.sports.entity.Student;
import pers.sports.service.StudentService;
import pers.sports.util.MD5Util;
import pers.sports.vo.LoginInfo;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class StudentServiceImpl implements StudentService {

    private final StudentDao studentDao;

    @Autowired
    public StudentServiceImpl(StudentDao studentDao) {
        this.studentDao = studentDao;
    }


    @Override
    @Transactional(readOnly = true)
    public Boolean StuPwdByNum(LoginInfo loginInfo) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String pwd;
        if (studentDao.findStuPwdByNum(loginInfo.getLoginName()) == null) {
            return false;
        } else {
            pwd = studentDao.findStuPwdByNum(loginInfo.getLoginName());
        }
        String md5pwd = MD5Util.encoderPassword(loginInfo.getPwd());
        return pwd.equals(md5pwd);
    }

    @Override
    @Transactional(readOnly = true)
    public Boolean StuEmailByNum(String stuNum, String email) {
        String new_email;
        if (studentDao.findStuEmailByNum(stuNum) == null) {
            return false;
        } else {
            new_email = studentDao.findStuEmailByNum(stuNum);
        }
        return email.equals(new_email);
    }

    @Override
    public void updatePwdByNum(String num, String pwd) {
        studentDao.updatePwdByNum(num, pwd);
    }

    @Override
    public String findStuIdByNum(String num) {
        return studentDao.findStuIdByNum(num);
    }

    @Override
    public Student findInfoByNum(String num) {
        return studentDao.findInfoByNum(num);
    }

    @Override
    public Boolean updateEmailById(String id, String email) {
        return studentDao.updateEmailById(id, email) != 0 ? true : false;
    }


}
